package com.zcaxer.way

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.CompoundButton
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zcaxer.way.adapters.BuildingAdapter
import com.zcaxer.way.databinding.ActivityHomeBinding
import com.zcaxer.way.viewmodels.BuildingViewModel
import com.zcaxer.way.viewmodels.BuildingViewModelFactory


class BuildingActivity : AppCompatActivity() {

    private lateinit var buildingViewModel: BuildingViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        Log.d("ttt1", "BuildingActivity onCreate")

        super.onCreate(savedInstanceState)
        val binding: ActivityHomeBinding = DataBindingUtil.setContentView(this, R.layout.activity_home)
        buildingViewModel = BuildingViewModelFactory(application)
                .create(BuildingViewModel::class.java)
        binding.lifecycleOwner = this
        binding.viewModel = buildingViewModel
        ArrayAdapter.createFromResource(
                this, R.array.spinner_target, R.layout.simple_spinner_item).also {
            it.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item)
            binding.spinner.adapter = it
        }
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView_buildingList)
        val layoutManager = LinearLayoutManager(this)
        val listeners = Listeners(this)
        val buildingAdapter = BuildingAdapter(buildingViewModel, listeners)
        recyclerView.apply {
            this.layoutManager = layoutManager
            adapter = buildingAdapter
            setHasFixedSize(false)
        }

        buildingViewModel.producer.observe(this, Observer {
            it?.let {
                buildingAdapter.submitList(it)
            }
        })

        binding.switchServant.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            buildingViewModel.servantFlag = isChecked
            buildingViewModel.saveServantFlag(isChecked)

        });
        binding.switchServant.isChecked=buildingViewModel.servantFlag
        binding.spinner.onItemSelectedListener = buildingViewModel
        buildingViewModel.createTimer()
    }

    override fun onResume() {
        super.onResume()
        //buildingViewModel.createTimer()
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("ttt1","building activity destroyed")
        buildingViewModel.timer.cancel()
    }
}
